/*
 * @Author: 曹宪辉
 * @Date: 2022-01-01 01:01:19
 * @Description: 
 * @FilePath: \RDA\src\RDA\FileModfiyMonitor.java
 */
package RDA;


import java.io.*;

public class FileModfiyMonitor {
    private long lastModified = 0L;

    public FileModfiyMonitor(long init){
        lastModified =  init;
    }

    public void checkFile(String path){
        if(path ==null || path.length() ==0) {
            return;
        }

        File file = new File(path);
        //System.out.println( file.getAbsoluteFile());
        if(!file.exists() || file.isDirectory()){
            return;
        }

        long _lastModified =  file.lastModified();
        if(_lastModified > lastModified){
            lastModified = _lastModified;
            try {
                FileReader reader = new FileReader(file);
                BufferedReader input = new BufferedReader(reader);
                String last = null, line;
                while ((line = input.readLine()) != null) {
                    last = line;
                }
                input.close();
                if(last!=null && alarmEvent!=null){
                    alarmEvent.alarm(path, last);
                }
            }catch (FileNotFoundException e) {
                e.printStackTrace();
            }catch (Exception ignored){
            }
        }
    }

    public static long getLastModify(String path){
        if(path ==null || path.length() ==0) {
            return 0L;
        }

        File file = new File(path);
        if(!file.exists() || file.isDirectory()){
            return 0L;
        }
        long modify = 0L;
        try {
            modify = file.lastModified();
        }catch (Exception ignored){
        }
        return modify;
    }

    public AlarmEvent getAlarmEvent() {
        return alarmEvent;
    }

    public void setAlarmEvent(AlarmEvent alarmEvent) {
        this.alarmEvent = alarmEvent;
    }

    public interface AlarmEvent{
        void alarm(String path,String msg);
    }

    /**
     * 文件修改日期更新后发送报警事件
     */
    private AlarmEvent alarmEvent;
}
